<?php
/*
 * class msg
 * Use for communication between php and php;
 * Create at: 12:08 2012/10/31
 * Author: leixun(lein_urg@163.com)
 * version 1 - 14:01 2012/10/31
 */

class msg{
	private $id;
	private $msg_id;
	private $_serialize = true;

	/**
	 * @param $_id ID
	 */
	public function msg($_id, $_serialize = true){
		if(!function_exists('msg_get_queue'))
		{
			die('msg queue function not installed, Reconfigure PHP with --enable-sysvmsg <br/>');
		}
		$this->id = $_id;
		$this->msg_id = msg_get_queue ( $_id );
		$this->_serialize = $_serialize;
		if ($this->msg_id === false) {
			die(basename(__FILE__).'->'.__LINE__.': Unable to create message quee');
		}
	}

	/**
	 * @data data to send
	 * @type message type
	 */
	public function send( $data, $type = 0, $blocking = false )
	{
		if (!msg_send ($this->msg_id, $type, $data, $this->_serialize, $blocking, $msg_err))
		{
			return "Msg not sent because $msg_err\n";
		}
		return true;
	}

	/**
	 * @param $type message type
	 * @param $maxsize The maximum size of message to be accepted,
	 */
	public function receive($no_wait = true, &$type , $maxsize = 1024 )
	{
		//bool msg_receive ( resource $queue , int $desiredmsgtype , int &$msgtype , int $maxsize , mixed &$message [, bool $unserialize = true [, int $flags = 0 [, int &$errorcode ]]] )
		$rs = msg_receive ( $this->msg_id , 0 ,	$type , $maxsize , $message , $this->_serialize, $no_wait?MSG_IPC_NOWAIT:NULL , $errorcode);
		if($rs)
			return $message;
		else
			return false;
	}

	public function remove()
	{
		msg_remove_queue($this->msg_id);
	}	
}